<template>
<div class="info-box">
    <div class="header-box" @click="getProjectClick()">
        <div v-if="!projectShow">
            <p><b style="color:red;">*</b>选择要预约的项目</p>
            <span>整形/皮肤/植发/口腔</span>
        </div>
        <div v-else>
            <div class="footer-box-style">
                <ul>
                    <Badge :content="index == '0' ? '主':''" v-for="(item, index) in projectList" :key="index">
                        <li>
                            {{item.name}}
                        </li>
                    </Badge>
                </ul>
            </div>
        </div>

    </div>
    <div class="date-time-box">
        <van-row>
            <van-col span="12">
                <div class="time-box time-box1">
                    <div class="time-box-header">
                        <p>到院日期</p><b>*</b>
                    </div>
                    <span @click="show = true">{{date}}</span>
                </div>

                <Calendar v-model="show" @confirm="onConfirm" />
            </van-col>
            <van-col span="12">
                <div class="time-box time-box2">
                    <div class="time-box-header">
                        <p>到院时间</p><b>*</b>
                    </div>

                    <span @click="timeShow = true">{{time}}</span>
                </div>

                <ActionSheet v-model="timeShow">
                    <div class="content">
                        <DatetimePicker :value="time" type="time" title="选择时间" :min-hour="formatDate(new Date) == date?minHour:''" @cancel="timeClose" @confirm="timeOk" />
                    </div>
                </ActionSheet>

            </van-col>
        </van-row>
        <van-row>
            <van-col span="12">
                <div class="time-box time-box1">
                    <div class="time-box-header">
                        <p>是否<br />好友陪同</p>
                    </div>
                    <span @click="phoneInputShow = true">{{friendPhoneData.length > 0 ? friendPhoneData.length : '否'}}</span>
                </div>

                <ActionSheet v-model="phoneInputShow">
                    <div class="content">
                        <ContactCard type="add" add-text="添加好友陪同" @click="userPhoneAdd()" />

                        <Field :value="item.phone" center clearable label="好友手机号码" placeholder="请输入好友手机号码" :maxlength="11" v-for="(item, index) in userPhoneArrData" :key="index" input-align="center" @input="(value) => phoneChange(value, index)" @blur="(e) => phoneBlur(e,index)">
                            <template #button>
                                <!-- :class="index == 0 && ('disabled-remove-click')" :disabled="index == 0" -->
                                <van-button size="small" type="danger" @click="removePhone(item)">删除</van-button>
                            </template>
                        </Field>
                        <p class="text-style">温馨提示：最多可增加三个陪同好友</p>
                        <van-button type="info" block @click="phoneAddClick()" class="btn2">添加陪同好友</van-button>
                    </div>
                </ActionSheet>

            </van-col>
            <van-col span="12">
                <div class="time-box time-box2">
                    <div class="time-box-header">
                        <p>是否<br />开车过来</p>
                    </div>
                    <span @click="cardCodeShow = true">{{cardBool?'是':'否'}}</span>
                </div>

                <ActionSheet v-model="cardCodeShow">
                    <div class="content" style="min-height:450px">
                        <park-component ref="parkComponent" />
                        <van-button type="info" block @click="cardCodeClick()" class="btn3">确认</van-button>
                    </div>
                </ActionSheet>
            </van-col>

        </van-row>
        <van-row>
            <van-col span="24">
                <van-field v-model="memo" rows="4" autosize type="textarea" placeholder="请输入备注信息" show-word-limit style="border-radius: 8px" />
            </van-col>
        </van-row>

        <van-button type="info" block @click="submitOk()" class="btn2">提交预约</van-button>
    </div>

    <float-icons padding="10 0 60 0" class="icons-warp">
        <div class="float-icon-item">
            <img src="../../../assets/dargIcon/back.png" alt="" @click="handleIcons('/home')" />
            <span>返回</span>
        </div>

    </float-icons>

</div>
</template>

<script>
import {
    Search,
    SwipeCell,
    Field,
    Badge,
    Toast,
    Image as VanImage,
    Dialog,
    IndexAnchor,
    IndexBar,
    Calendar,
    ActionSheet,
    DatetimePicker,
    ContactCard
} from 'vant';
import FloatIcons from '@/components/s-icons'
import parkComponent from './components/Dispense'
import {
    submitDeptSchedulerInfo
} from '../../../sgApi/index'
import {
    isbind
} from "../../isCheckBind.js"

export default {
    components: {
        Search,
        SwipeCell,
        Field,
        VanImage,
        Badge,
        IndexAnchor,
        IndexBar,
        Calendar,
        ActionSheet,
        DatetimePicker,
        ContactCard,
        parkComponent,
        FloatIcons
    },
    name: "preferenceItemsInfo",
    data() {
        return {

            currentDate: new Date(),
            show: false,
            // this.formatDate(new Date())
            date: "请选择",

            minHour: new Date().getHours() + 1,
            timeShow: false,
            // this.formatTime(new Date())
            time: "请选择",

            projectShow: false,
            projectList: [],

            phoneInputShow: false,

            userPhoneArrData: [{
                phone: '',
                id: 1
            }],
            num: 1,
            friendPhoneData: [],
            memo: '',

            cardCodeShow: false,
            cardBool: false,
            cardNum: '',

        }
    },
    mounted() {

    },
    created() {
        isbind()
        let preferenceInfo = localStorage.getItem("preferenceInfo") ? JSON.parse(localStorage.getItem("preferenceInfo")) : null
        if (preferenceInfo) {
            let projectData = preferenceInfo
            this.projectShow = true
            this.projectList = projectData
        } else {
            this.projectShow = false
        }

    },
    methods: {
        handleIcons(id) {
            this.$router.replace({
                path: "/preferenceItems"
            })
        },
        formatDate(date) {
            return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        },
        formatTime(time) {
            return `${time.getHours() < 10 ? '0' + time.getHours():time.getHours()}:${time.getMinutes() < 10 ? '0'+time.getMinutes():time.getMinutes()}`;
        },
        onConfirm(date) {
            this.show = false;
            this.date = this.formatDate(date);
            if (this.formatDate(date) == this.formatDate(new Date())) {
                this.time = this.formatTime(new Date())
            }
        },
        timeOnConfirm() {
            this.timeShow = false;
        },
        timeClose() {
            this.timeShow = false;
        },
        timeOk(value) {
            console.log(value)
            this.timeShow = false;
            this.time = value
        },

        getProjectClick() {
            this.$router.replace({
                path: '/preferenceItems',
                // query:{
                //     project: JSON.stringify(this.projectList).toString()
                // }
            })
        },

        userPhoneAdd() {
            if (this.userPhoneArrData.length < 3) {
                this.userPhoneArrData.push({
                    phone: '',
                    id: this.num + 1
                })
                this.num += 1
            } else {
                Toast.fail('最多可增加三个陪同好友')
            }

        },
        phoneChange(value, index) {
            this.userPhoneArrData[index].phone = value.replace(/\D/g, '')
            this.userPhoneArrData = [...this.userPhoneArrData]
        },
        phoneBlur(e, index) {
            const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
            if (!reg.test(e.target.value)) {

                Toast.fail({
                    message: '请输入正确的11位手机号',
                    forbidClick: true,
                });
                this.userPhoneArrData[index].phone = ''
                this.userPhoneArrData = [...this.userPhoneArrData]
                return false
            }
        },
        removePhone(value) {
            let newData = this.userPhoneArrData.filter(item => {
                return item.id != value.id
            })
            this.userPhoneArrData = [...newData]

            if (value.phone != '') {
                let newData2 = this.friendPhoneData.filter(item => {
                    return item.id != value.id
                })
                this.friendPhoneData = [...newData2]
            }

        },

        phoneAddClick() {

            let newData = this.userPhoneArrData.filter(item => {
                return item.phone != ''
            })
            console.log(newData)
            if (newData.length > 0) {
                console.log(newData)
                this.friendPhoneData = [...newData]
                this.phoneInputShow = false
            } else {
                Toast.fail('请先输入陪同好友的手机号')
            }
        },

        cardCodeClick() {
            this.cardCodeShow = false
            let refData = this.$refs.parkComponent
            let cardNum = refData.areaName + refData.areaLetter + refData.numOne + refData.numTwo + refData.numThree + refData.numFour + refData.numFive + refData.numSix
            console.log(cardNum)

            this.cardNum = cardNum
            if (cardNum != '') {
                this.cardBool = true
            } else {
                this.cardBool = false
            }
        },

        submitOk() {
            // {"customerCrmId":"20210607212435423308","memo":"测试备注信息","sch_date":"2021-12-28","time":"1","customer_name":"李浩","data":[{"tb_client_demand_id":"20140806171748057000","demand_name":"眼眉部整形","is_main":"1"},{"tb_client_demand_id":"20200520164448898000","demand_name":"祛痘/痘疤/痘印/痘坑","is_main":"0"},{"tb_client_demand_id":"20210623180516618000","demand_name":"三分钟无痕祛眼袋","is_main":"0"}]}

            // ##
            // sch_date：预约日期
            // time: ：1=上午，2=下午，3=不确定
            // is_main：是否主诉项目
            // memo：备注信息
            console.log(this.projectList)

            if (this.projectList.length < 1) {
                Toast.fail('请先选择预约项目')
                return false
            }

            if (this.date == "请选择") {
                Toast.fail('请选择到院日期')
                return false
            }

            if (this.time == "请选择") {
                Toast.fail('请选择到院时间')
                return false
            }

            Dialog.confirm({
                title: '提示',
                message: `是否确定预约`,
            }).then(() => {
                let newProjectData = this.projectList.map((item, index) => {
                    return {
                        tb_client_demand_id: item.tb_client_demand_id,
                        demand_name: item.name,
                        is_main: (index == 0 ? 1 : 0)
                    }
                })
                let phoneString = ''
                this.friendPhoneData.forEach(item => {
                    phoneString += item.phone + ','
                })

                let sendData = {
                    customerCrmId: localStorage.getItem("customerCrmId"),
                    customer_name: JSON.parse(localStorage.getItem("obj")).customerName,

                    data: newProjectData,
                    sch_date: this.date,
                    time: this.time,
                    memo: this.memo,
                    car_no: this.cardNum,
                    peitong_mobilestr: phoneString
                }
                console.log(sendData)

                submitDeptSchedulerInfo(sendData).then(res => {
                    if (res.code == 0) {

                        localStorage.removeItem("preferenceInfo")
                        Toast.success(res.msg)
                        setTimeout(() => {
                            this.$router.replace({
                                path: "/memberCenter"
                            })
                        }, 1800)

                    } else {
                        Toast.fail(res.msg)
                    }
                })

            }).catch(() => {
                console.log('err')
            });

        }
    }

}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
